# -*- coding: utf-8 -*-
# @Author  : pony.guan
# @Time    : 2022/5/26 17:41
# Description: 空箱出库

import os
import json
import time
from contextlib import contextmanager

import pymysql
import requests
import yaml


@contextmanager
def cursor_context(ip: str, db: str = 'booktopia'):
    """
    @desc mysql 连接
    :param ip:
    :param db:
    :return:
    """
    config = {'host': ip, 'port': 3306, 'user': 'root', 'passwd': 'root', 'db': db, 'charset': 'utf8'}
    conn = pymysql.connect(**config)
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        yield cursor
        conn.commit()
    except:
        conn.rollback()
        raise
    finally:
        cursor.close()
        conn.close()


def get_empty_bin_codes(quantity: int = 10, all_: bool = False) -> list:
    """
    @获取空箱
    :param quantity:
    :param all_:
    :return:
    """
    with cursor_context(ip, 'booktopia') as sc:
        quantity = quantity if not all_ else 100000000
        sql = "select code from ks_bin where code  is not null and status='BIN_NORMAL' and is_empty=1 limit %s"
        sc.execute(sql, (quantity,))
        rows = sc.fetchall()
    empty_bin_codes = [row['code'] for row in rows]
    return empty_bin_codes


def send_request(empty_bin_codes: list):
    """
    @desc 空箱出库请求
    :param empty_bin_codes:
    :return:
    """
    url = f'http://{ip}:9090/countOutbound/create'
    tote_list = []
    for index, empty_bin_code in enumerate(empty_bin_codes):
        tote_list.append(
            {
                "taskCode": f'task_{index + 1}_{time.time()}',
                # "stockToteCode": empty_bin_code,
                "stockToteCode": None
            }
        )
    headers = {
        "warehouseCode": "Booktopia",
        "requestId": time.strftime('%Y%m%d%H%M%S'),
        "Content-Type": "application/json"
    }

    data = {
        "taskType": 1,
        "priority": 0,
        "emptyToteQty": len(tote_list),
        "outboundToteList": tote_list
    }

    r = requests.post(url=url, data=json.dumps(data), headers=headers)
    print(r.json())
    return r.status_code == 200 or str(r.text)


with open('config.yml') as f:
    json_ = yaml.load(f.read(), Loader=yaml.FullLoader)
ip = json_['ip']
# all_ = json_['empty_container_move_out_checked']['all']
# quantity = json_['empty_container_move_out_checked']['quantity']
# print(quantity)
if __name__ == '__main__':

    # 安装依赖包
    os.system("pip3 install "
              "PyYAML "
              "PyMySQL==0.9.3  "
              "requests "
              "-i http://pypi.douban.com/simple/")

    empty_bin_codes = get_empty_bin_codes(quantity, all_)
    ret = send_request(empty_bin_codes)
    if ret is True:
        print('finished')
    else:
        print('---error----:')
        print(ret)
